<?php

class ProductForm extends TPage
{
	const AR = "ProductRecord";
	const NO_IMAGE = "noimage.png";
	public function onLoad($param)
	{
		parent::onLoad($param);
		$this->Master->pageHead->Title = $this->Application->Parameters["WEBSITE_TITLE"] . " Administrator";
		if (!$this->IsPostBack)
		{
			// fill parent selector combobox
			$this->cboCatSelector->DataSource = CategoryRecord::finder()->getCategoryTree(true);
			$this->cboCatSelector->DataBind();
			$this->cboBrandSelector->DataSource = BrandRecord::finder()->getAllItems();
			$this->cboBrandSelector->DataBind();						
			
			$activeRecord = $this->getItem();
			if ($activeRecord && $activeRecord->ID > 0)
			{
				// Populates the input controls with the existing post data
				$this->lblHeader->Text = "Update product: ".$activeRecord->Name;
				$this->txtName->Text = $activeRecord->Name;
				$this->cboBrandSelector->SelectedValue = $activeRecord->BrandID;
				$this->cboCatSelector->SelectedValues = $activeRecord->CategoryIDs;
				$this->txtPrice->Text = $activeRecord->Price;
				$this->txtStock->Text = $activeRecord->Stock;
				$this->radPublish->SelectedValue = $activeRecord->IsPublished;
				$this->radNewArrival->SelectedValue = $activeRecord->IsNewArrival;
				$this->radHotDeal->SelectedValue = $activeRecord->IsHotDeal;
				$this->radBestSeller->SelectedValue = $activeRecord->IsBestSeller;
				$this->txtBrief->Text = $activeRecord->Brief;
				$this->txtDesc->Text = $activeRecord->Description;
				$this->imgFull->Visible = true;
				$this->imgFull->ImageUrl = $this->Request->UrlManagerModule->UrlPrefix."/useruploads/images/product/".$activeRecord->ImagePath;
				$this->imgThumb->Visible = true;
				$this->imgThumb->ImageUrl = $this->Request->UrlManagerModule->UrlPrefix."/useruploads/images/product/thumbs/".$activeRecord->ThumbnailPath;
				$this->imgThumbLatest->Visible = true;
				$this->imgThumbLatest->ImageUrl = $this->Request->UrlManagerModule->UrlPrefix."/useruploads/images/product/thumbs/".$activeRecord->ImageNewArrivalPath;
				$this->imgThumbExclusive->Visible = true;
				$this->imgThumbExclusive->ImageUrl = $this->Request->UrlManagerModule->UrlPrefix."/useruploads/images/product/thumbs/".$activeRecord->ImageHotDealPath;
				$this->imgThumbPromotion->Visible = true;
				$this->imgThumbPromotion->ImageUrl = $this->Request->UrlManagerModule->UrlPrefix."/useruploads/images/product/thumbs/".$activeRecord->ImageBestSellerPath;
			}
			else
			{
				$this->lblHeader->Text = "Add new product";
			}
		}
	}

	protected function getItem()
	{
		if ($this->Request->Contains("id") && $this->Request->Contains("alias"))
		{
			// use Active Record to look for the specified post ID
			$activeRecord = Prado::createComponent(self::AR)->finder()->findByproduct_idAndproduct_alias(TPropertyValue::ensureInteger($this->Request['id']), $this->Request['alias']);
			if($activeRecord === null)
			{
				$this->Notice->Type = AdminNoticeType::Error;
				$this->Notice->Text = $this->Application->getModule("message")->translate("ITEM_NOT_FOUND","product");
				$this->mainBox->Visible = false;
			}
			return $activeRecord;
		}
		else
		{
			return Prado::createComponent(self::AR);
		}
	}
		
	private function bindItem()
	{
		$activeRecord = $this->getItem();

		$hashImage = "";
		if($this->fuImage->HasFile) 
		{
			$hashImage = md5(uniqid(time())).'.'.strtolower(array_pop(explode('.',$this->fuImage->FileName)));
			$filePath = dirname($this->Request->ApplicationFilePath).DIRECTORY_SEPARATOR."useruploads".DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR."product".DIRECTORY_SEPARATOR;
			if ($activeRecord->ImagePath != '' && $activeRecord->ImagePath != self::NO_IMAGE) 
			{
				// Delete old image
				try
				{
					chmod($filePath.$activeRecord->ImagePath, 0777);
					unlink($filePath.$activeRecord->ImagePath);
				}
				catch(TException $e){}
			}

			$this->fuImage->saveAs($filePath.$hashImage, true);
		}

		$hashThumb = "";
		if($this->fuThumb->HasFile) 
		{
			$hashThumb = md5(uniqid(time())).'.'.strtolower(array_pop(explode('.',$this->fuThumb->FileName)));
			$filePath = dirname($this->Request->ApplicationFilePath).DIRECTORY_SEPARATOR."useruploads".DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR."product".DIRECTORY_SEPARATOR."thumbs".DIRECTORY_SEPARATOR;
			if ($activeRecord->ThumbnailPath != '' && $activeRecord->ThumbnailPath != self::NO_IMAGE) 
			{
				// Delete old thumbnail
				try
				{
					chmod($filePath.$activeRecord->ThumbnailPath, 0777);
					unlink($filePath.$activeRecord->ThumbnailPath);
				}
				catch(TException $e){}
			}

			$this->fuThumb->saveAs($filePath.$hashThumb, true);
		}
		
		$hashThumbLatest = "";
		if($this->fuThumbLatest->HasFile) 
		{
			$hashThumbLatest = md5(uniqid(time())).'.'.strtolower(array_pop(explode('.',$this->fuThumbLatest->FileName)));
			$filePath = dirname($this->Request->ApplicationFilePath).DIRECTORY_SEPARATOR."useruploads".DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR."product".DIRECTORY_SEPARATOR."thumbs".DIRECTORY_SEPARATOR;
			if ($activeRecord->ImageNewArrivalPath != '' && $activeRecord->ImageNewArrivalPath != self::NO_IMAGE) 
			{
				// Delete old image
				try
				{
					chmod($filePath.$activeRecord->ImageNewArrivalPath, 0777);
					unlink($filePath.$activeRecord->ImageNewArrivalPath);
				}
				catch(TException $e){}
			}

			$this->fuThumbLatest->saveAs($filePath.$hashThumbLatest, true);
		}
		
		$hashThumbExclusive = "";
		if($this->fuThumbExclusive->HasFile) 
		{
			$hashThumbExclusive = md5(uniqid(time())).'.'.strtolower(array_pop(explode('.',$this->fuThumbExclusive->FileName)));
			$filePath = dirname($this->Request->ApplicationFilePath).DIRECTORY_SEPARATOR."useruploads".DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR."product".DIRECTORY_SEPARATOR."thumbs".DIRECTORY_SEPARATOR;
			if ($activeRecord->ImageHotDealPath != '' && $activeRecord->ImageHotDealPath != self::NO_IMAGE) 
			{
				// Delete old image
				try
				{
					chmod($filePath.$activeRecord->ImageHotDealPath, 0777);
					unlink($filePath.$activeRecord->ImageHotDealPath);
				}
				catch(TException $e){}
			}

			$this->fuThumbExclusive->saveAs($filePath.$hashThumbExclusive, true);
		}
		
		$hashThumbPromotion = "";
		if($this->fuThumbPromotion->HasFile) 
		{
			$hashThumbPromotion = md5(uniqid(time())).'.'.strtolower(array_pop(explode('.',$this->fuThumbPromotion->FileName)));
			$filePath = dirname($this->Request->ApplicationFilePath).DIRECTORY_SEPARATOR."useruploads".DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR."product".DIRECTORY_SEPARATOR."thumbs".DIRECTORY_SEPARATOR;
			if ($activeRecord->ImageBestSellerPath != '' && $activeRecord->ImageBestSellerPath != self::NO_IMAGE) 
			{
				// Delete old image
				try
				{
					chmod($filePath.$activeRecord->ImageBestSellerPath, 0777);
					unlink($filePath.$activeRecord->ImageBestSellerPath);
				}
				catch(TException $e){}
			}

			$this->fuThumbPromotion->saveAs($filePath.$hashThumbPromotion, true);
		}

		$activeRecord->Name = $this->txtName->SafeText;
		$activeRecord->Alias = "";
		$activeRecord->BrandID = $this->cboBrandSelector->SelectedValue;		
		$activeRecord->Price = TPropertyValue::ensureFloat($this->txtPrice->Text);
		$activeRecord->Stock = TPropertyValue::ensureInteger($this->txtStock->Text);
		$activeRecord->IsPublished = $this->radPublish->SelectedValue;
		$activeRecord->IsNewArrival = $this->radNewArrival->SelectedValue;
		$activeRecord->IsHotDeal = $this->radHotDeal->SelectedValue;
		$activeRecord->IsBestSeller = $this->radBestSeller->SelectedValue;
		$activeRecord->Brief = $this->txtBrief->SafeText;
		$activeRecord->Description = $this->txtDesc->Text;
		$activeRecord->ImagePath = (strlen($hashImage)>0)?$hashImage:($activeRecord->ID>0?$activeRecord->ImagePath:self::NO_IMAGE);
		$activeRecord->ThumbnailPath = (strlen($hashThumb)>0)?$hashThumb:($activeRecord->ID>0?$activeRecord->ThumbnailPath:self::NO_IMAGE);
		$activeRecord->ImageNewArrivalPath = (strlen($hashThumbLatest)>0)?$hashThumbLatest:($activeRecord->ID>0?$activeRecord->ImageNewArrivalPath:self::NO_IMAGE);
		$activeRecord->ImageHotDealPath = (strlen($hashThumbExclusive)>0)?$hashThumbExclusive:($activeRecord->ID>0?$activeRecord->ImageHotDealPath:self::NO_IMAGE);
		$activeRecord->ImageBestSellerPath = (strlen($hashThumbPromotion)>0)?$hashThumbPromotion:($activeRecord->ID>0?$activeRecord->ImageBestSellerPath:self::NO_IMAGE);
		
		return $activeRecord;
	}

	protected function btnSubmit_Clicked($sender, $param)
	{
		if ($this->IsValid)
		{
			$activeRecord = $this->bindItem();
			try
			{
				$action = ($activeRecord->ID>0 ? "update-success" : "add-success");
				$msg = $this->Application->getModule("message")->translate(($activeRecord->ID>0 ? "UPDATE_SUCCESS" : "ADD_SUCCESS"),"Product",$activeRecord->Name);
				$activeRecord->save();
				if ($activeRecord->ID>0)
				{
					$criteria = new TActiveRecordCriteria;
					$criteria->Condition = "product_id = :id";
					$criteria->Parameters[":id"] = $activeRecord->ID;
					ProductCatRecord::finder()->deleteAll($criteria);
				}
				foreach($this->cboCatSelector->SelectedValues as $catID)
				{
					$productCat = new ProductCatRecord(array("ProductID"=>$activeRecord->ID,"CatID"=>$catID));
					$productCat->save();
				}

				if (strlen($this->Request["refUrl"])>0)
					$url = urldecode($this->Request["refUrl"])."&action=$action&msg=$msg";
				else  
					$url = $this->Service->ConstructUrl("admin.ManageProducts",array("action"=>$action, "msg"=>$msg));
				$this->Response->redirect($url);
			}
			catch(TException $e)
			{
				$this->Notice->Type = AdminNoticeType::Error;
				$this->Notice->Text = $this->Application->getModule("message")->translate(($activeRecord->ID>0 ? "UPDATE_FAILED" : "ADD_FAILED"),"Product",$activeRecord->Name);
			}
		}
	}

	protected function uniqueCheck_ServerValidated($sender, $param)
	{
		if ($param->Value != '')
		{
			$criteria = new TActiveRecordCriteria;
			$criteria->Condition = "product_name = :name";
			$criteria->Parameters[":name"] = $param->Value;
			$activeRecord = $this->getItem();
			if ($activeRecord && $activeRecord->ID > 0) $criteria->Condition .= " and product_id <> '".$activeRecord->ID."'";
			$param->IsValid = count(Prado::createComponent(self::AR)->finder()->find($criteria)) == 0;
		}
	}	

	protected function checkImageExtension_ServerValidated($sender, $param)
	{
		if ($param->Value != '') 
			$param->IsValid = in_array(strtolower(array_pop(explode('.', $param->Value))), TPropertyValue::ensureArray($this->Application->Parameters['AVAILABLE_IMAGES']));
	}
}

?>